const express = require('express');
const router = express.Router();
const myMulter = require('../lib/middleware/myMulter');
const User = require('../database/redis/userDao');
const verify = require('../lib/controller/verify');

router.get('/', function (req, res, next) {
    //如果已经登录直接重定义
    if (req.session.userId) {
        res.redirect("/");
        return
    }

    res.render('register');
});

router.post('/', myMulter, async function (req, res, next) {

    let account = req.body.account;
    let password = req.body.password;
    let re_password = req.body.re_password;
    let sex = req.body.sex;
    let email = req.body.email;
    let resume = req.body.resume;
    let adminSelect = req.body.adminSelect;
    let adminKey = req.body.adminKey;
    let avatarFileName = null;

    //req.file存在说明multer收到图片了。。
    if (req.file) {
        avatarFileName = req.file.filename;
    }

    let status = await verify.asyncRegisterVerify(req, account, password, re_password, email, resume,adminSelect,adminKey);
    //返回ture是通过校验~
    if (status === true) {
        let user = new User({
            account,
            password,
            sex,
            email,
            resume,
            avatarFileName,
            //如果选择了管理员，上边则已经校验过密钥了
            //adminSelect为1是管理员，为0是普通用户
            level:adminSelect
        });

        //保存
        await user.asyncSave();

        //用户信息写入session
        req.session.userId = await User.asyncGetIdByAccount(account);
        res.redirect('/');
        return
    }

    res.render('register');
    return
});

module.exports = router;